<template>
  <div class="hello">
    <div id="container" style=" width: 100%;height: 100%;"></div>
    <div class="input-card">
      <h5 class="title" style="top:5rem;margin-bottom:5px">
        上海市537路公交车线路查询
      </h5>
      <el-form :model="busForm" ref="busForm" label-width="80px" :inline="true">
        <el-form-item
          label="线路方向"
          :rules="{
            required: true,
            message: '请选择路线方向',
            trigger: 'change',
          }"
          style="margin-bottom: 16px"
          prop="busType"
        >
          <el-select
            size="small"
            style="margin-left:5px;width:13rem"
            v-model="busForm.busType"
            placeholder="请先选择路线方向"
            clearable
            @change="changeBusType"
          >
            <!-- @clear="clearBusType" -->
            <el-option
              v-for="item in busTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="起始站点"
          :rules="{
            required: true,
            message: '请选择起始站点',
            trigger: 'change',
          }"
          style="margin-bottom: 16px"
          prop="startStop"
          key="1"
        >
          <el-select
            size="small"
            style="margin-left:5px;width:13rem;"
            v-model="busForm.startStop"
            placeholder="请选择起始站点"
            clearable
            value-key="id"
          >
            <el-option
              v-for="item in stopOptions"
              :key="item.id"
              :label="item.name"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="末尾站点"
          :rules="{
            required: true,
            message: '请选择末尾站点',
            trigger: 'change',
          }"
          prop="endStop"
          key="2"
        >
          <el-select
            size="small"
            style="margin-left:5px;width:13rem"
            v-model="busForm.endStop"
            placeholder="请选择末尾站点"
            clearable
            value-key="id"
          >
            <el-option
              v-for="item in stopOptions"
              :key="item.id"
              :label="item.name"
              :value="item"
            >
            </el-option> </el-select
        ></el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            style="margin-left:5px;"
            @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import AMap from "AMap"; // 引入高德地图
export default {
  name: "BusStop",
  props: {
    msg: String,
  },
  data() {
    return {
      // 表单
      busForm: { busType: "", startStop: {}, endStop: {} },
      // 路线方向选项
      busTypeOptions: [
        {
          value: "1",
          label: "上行（开往老西门路方向）",
        },
        {
          value: "2",
          label: "下行（开往鲁路白城路方向）",
        },
      ],
      mapObj: "",
      // 保存公交路线选项
      optionsUp: [],
      optionsDown: [],
      // stopOptions: [
      //   { name: "老西门", sequence: 1 },
      //   { name: "西藏南路淮海东路", sequence: 2 },
      //   { name: "人民广场(广东路)", sequence: 3 },
      //   { name: "西藏中路北京东路", sequence: 4 },
      //   { name: "天目东路山西北路", sequence: 5 },
      //   { name: "宝山路鸿兴路", sequence: 6 },
      //   { name: "东江湾路同心路", sequence: 7 },
      //   { name: "虹口足球场", sequence: 8 },
      //   { name: "上农新村", sequence: 9 },
      //   { name: "中山北一路新华一村", sequence: 10 },
      //   { name: "大柏树(逸仙路)", sequence: 11 },
      //   { name: "逸仙路纪念路", sequence: 12 },
      //   { name: "仁德路逸仙路", sequence: 13 },
      //   { name: "武东路吉浦路", sequence: 14 },
      //   { name: "武川路武东路", sequence: 15 },
      //   { name: "政立路武川路", sequence: 16 },
      //   { name: "政立路国定路", sequence: 17 },
      //   { name: "政立路市光路", sequence: 18 },
      //   { name: "长海路黑山路", sequence: 19 },
      //   { name: "长海医院", sequence: 20 },
      //   { name: "中原路国和路", sequence: 21 },
      //   { name: "中原路市光路", sequence: 22 },
      //   { name: "市光路包头路", sequence: 23 },
      //   { name: "市光路白城路", sequence: 24 },
      //   { name: "开鲁路白城路", sequence: 25 },
      // ],
      stopOptions: [],
    };
  },
  created() {
    //methods和data已经初始化,常用于操作数据，发起ajax请求
    // console.log(window.screen.height);
    // console.log(window.screen.width);
    // 已载入高德地图API，则直接初始化地图
    // 另一种写法，地址：https://github.com/zuley/vue-gaode/blob/master/src/components/mapDrag.vue
    // if (window.AMap && window.AMapUI) {
    //   this.initMap()
    // // 未载入高德地图API，则先载入API再初始化
    // } else {
    //   // 载入高德地图和UI组件
    //   Promise.all([
    //     remoteLoad(`http://webapi.amap.com/maps?v=1.3&key=${MapKey}`),
    //     remoteLoad('http://webapi.amap.com/ui/1.0/main.js')
    //   ]).then(() => {
    //     this.initMap()
    //   })
    // }
  },
  mounted() {
    // 初始化地图
    this.init();
  },
  methods: {
    init() {
      // 新建地图对象实例
      let that = this;
      let map = new AMap.Map("container", {
        // center: this.center,
        resizeEnable: true,
        zoom: 10,
      });
      that.mapObj = map;
      // 启用工具条
      AMap.plugin(["AMap.ToolBar", "AMap.OverView"], function() {
        map.addControl(
          new AMap.ToolBar({
            position: "RT", //左上
          })
        );
        map.addControl(new AMap.OverView({ isOpen: false }));
      });
      AMap.plugin("AMap.Geolocation", function() {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
          // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
          buttonOffset: new AMap.Pixel(10, 20),
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true,
          //  定位按钮的排放位置,  RB表示右下
          buttonPosition: "RB",
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete);
        AMap.event.addListener(geolocation, "error", onError);
        function onComplete(data) {
          // data是具体的定位信息
          // console.log(data);
        }
        function onError(data) {
          // 定位出错
          console.log(data);
        }
      });
      AMap.plugin(["AMap.LineSearch"], function() {
        //实例化公交线路查询类
        var linesearch = new AMap.LineSearch({
          pageIndex: 1, //页码，默认值为1
          pageSize: 1, //单页显示结果条数，默认值为20，最大值为50
          city: "上海", //限定查询城市，可以是城市名（中文/中文全拼）、城市编码，默认值为『全国』
          extensions: "all", //是否返回公交线路详细信息，默认值为『base』
        });
        map.addControl(linesearch);
        //执行公交路线关键字查询
        linesearch.search("537", function(status, result) {
          //打印状态信息status和结果信息result
          // console.log(result);
          // console.log(result.lineInfo[0].via_stops);
          // let arr = [];
          // let origin = result.lineInfo[0].via_stops;
          // for (const key in origin) {
          //   arr.push({});
          // }
          // 上行需要反转数组
          // Object.freeze(result.lineInfo[0].via_stops);
          that.optionsUp = result.lineInfo[0].via_stops;
          that.optionsUp.reverse();
          // 下行直接复制
          that.optionsDown = Object.assign([], result.lineInfo[0].via_stops);
          // 因为result.lineInfo[0].via_stops已经被defineProperty过，直接反转会导致两个数组状态一致
          // console.log(that.optionsDown);
          // that.optionsUp.sort((a, b) => {
          //   return b.sequence - a.sequence;
          // });
        });
      });
      //调用transfer这个工具类
      AMap.service("AMap.Transfer", function() {});
    },
    // 路线方向选择后触发
    changeBusType(e) {
      // console.log(e);
      if (e == 1) {
        this.stopOptions = this.optionsUp;
      } else if (e == 2) {
        this.stopOptions = this.optionsDown;
      } else {
        this.busForm.startStop = "";
        this.busForm.endStop = "";
        this.stopOptions = [];
      }
    },
    // 路线方向清空时操作
    // clearBusType() {
    //   // this.stopOptions = [];
    //   // console.log(11);
    //   this.busForm.startStop = "";
    //   this.busForm.endStop = "";
    // },
    //判断路线方向是否选择
    // confirm() {
    //   if (this.busForm.busType == "") {
    //     this.stopOptions = [];
    //   }
    // },
    // 查询
    search() {
      let that = this;
      this.$refs["busForm"].validate((valid) => {
        if (valid) {
          // 查询动作，以及后续的画图操作
          // console.log(this.mapObj);
          var transferOption = {
            city: "上海市",
            policy: window.AMap.TransferPolicy.LEAST_TIME, // 其它policy取值请参照 https://lbs.amap.com/api/javascript-api/reference/route-search#m_TransferPolicy
          };
          var transfer = new AMap.Transfer(transferOption);
          //根据起、终点坐标查询公交换乘路线
          transfer.search(
            new AMap.LngLat(
              this.busForm.startStop.location.lng,
              this.busForm.startStop.location.lat
            ),
            new AMap.LngLat(
              this.busForm.endStop.location.lng,
              this.busForm.endStop.location.lat
            ),
            function(status, result) {
              // result即是对应的公交路线数据信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_TransferResult
              if (status === "complete") {
                if (result.plans && result.plans.length) {
                  console.log("绘制公交路线完成");
                  that.drawRoute(result.plans[0]);
                }
              } else {
                console.log.error("公交路线数据查询失败" + result);
              }
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 绘制路线
    drawRoute(route) {
      var startMarker = new AMap.Marker({
        position: route.segments[0].transit.origin,
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
        map: this.mapObj,
      });
      var endMarker = new AMap.Marker({
        position: route.segments[route.segments.length - 1].transit.destination,
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
        map: this.mapObj,
      });
      var routeLines = [];
      for (var i = 0, l = route.segments.length; i < l; i++) {
        var segment = route.segments[i];
        var line = null;
        // 绘制步行路线
        if (segment.transit_mode === "WALK") {
          line = new AMap.Polyline({
            path: segment.transit.path,
            isOutline: true,
            outlineColor: "#ffeeee",
            borderWeight: 2,
            strokeWeight: 5,
            strokeColor: "grey",
            lineJoin: "round",
            strokeStyle: "dashed",
          });
          line.setMap(this.mapObj);
          routeLines.push(line);
        } else if (
          segment.transit_mode === "SUBWAY" ||
          segment.transit_mode === "BUS"
        ) {
          line = new AMap.Polyline({
            path: segment.transit.path,
            isOutline: true,
            outlineColor: "#ffeeee",
            borderWeight: 2,
            strokeWeight: 5,
            strokeColor: "#0091ff",
            lineJoin: "round",
            strokeStyle: "solid",
          });
          line.setMap(this.mapObj);
          routeLines.push(line);
        } else {
          // 其它transit_mode的情况如RAILWAY、TAXI等，该示例中不做处理
        }
      }
      // 调整视野达到最佳显示区域
      this.mapObj.setFitView([startMarker, endMarker].concat(routeLines));
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
  width: 1600px;
  height: 756px;
}
@media screen and (min-width: 1700px) {
  .hello {
    width: 1920px;
    height: 1080px;
  }
}
.title {
  margin: 0 0;
  padding: 0 0;
}
.input-card {
  width: 19rem;
  position: fixed;
  left: 1rem;
  top: 1rem;
  background-color: #fff;
  background-clip: border-box;
  min-width: 0;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  padding: 0.75rem 1.25rem 0 1.25rem;
}
</style>
